package com.example.idachuappone.index.weixinpay;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import junit.framework.Assert;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.util.Log;

public class Util {
	private static final int MAX_DECODE_PICTURE_SIZE = 2764800;
	private static final String TAG = "SDK_Sample.Util";

	private static class SSLSocketFactoryEx extends SSLSocketFactory {
		SSLContext sslContext;

		public SSLSocketFactoryEx(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException,
				KeyStoreException, UnrecoverableKeyException {
			super(truststore);
			this.sslContext = SSLContext.getInstance("TLS");
			TrustManager tm = new X509TrustManager() {
				@Override
				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}

				@Override
				public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
				}

				@Override
				public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
				}
			};
			this.sslContext.init(null, new TrustManager[] { tm }, null);
		}

		@Override
		public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException,
				UnknownHostException {
			return this.sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
		}

		@Override
		public Socket createSocket() throws IOException {
			return this.sslContext.getSocketFactory().createSocket();
		}
	}

	public static byte[] bmpToByteArray(Bitmap bmp, boolean needRecycle) {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		bmp.compress(CompressFormat.PNG, 100, output);
		if (needRecycle) {
			bmp.recycle();
		}
		byte[] result = output.toByteArray();
		try {
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static byte[] httpGet(String url) {
		byte[] bArr = null;
		if (url == null || url.length() == 0) {
			Log.e(TAG, "httpGet, url is null");
		} else {
			try {
				HttpResponse resp = getNewHttpClient().execute(new HttpGet(url));
				if (resp.getStatusLine().getStatusCode() != 200) {
					Log.e(TAG, "httpGet fail, status code = " + resp.getStatusLine().getStatusCode());
				} else {
					bArr = EntityUtils.toByteArray(resp.getEntity());
				}
			} catch (Exception e) {
				Log.e(TAG, "httpGet exception, e = " + e.getMessage());
				e.printStackTrace();
			}
		}
		return bArr;
	}

	public static byte[] httpPost(String url, String entity) {
		byte[] bArr = null;
		if (url == null || url.length() == 0) {
			Log.e(TAG, "httpPost, url is null");
		} else {
			HttpClient httpClient = getNewHttpClient();
			HttpPost httpPost = new HttpPost(url);
			try {
				httpPost.setEntity(new StringEntity(entity));
				httpPost.setHeader("Accept", "application/json");
				httpPost.setHeader("Content-type", "application/json");
				HttpResponse resp = httpClient.execute(httpPost);
				if (resp.getStatusLine().getStatusCode() != 200) {
					Log.e(TAG, "httpGet fail, status code = " + resp.getStatusLine().getStatusCode());
				} else {
					bArr = EntityUtils.toByteArray(resp.getEntity());
				}
			} catch (Exception e) {
				Log.e(TAG, "httpPost exception, e = " + e.getMessage());
				e.printStackTrace();
			}
		}
		return bArr;
	}

	private static HttpClient getNewHttpClient() {
		try {
			KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
			trustStore.load(null, null);
			SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
			sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			HttpParams params = new BasicHttpParams();
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, "UTF-8");
			SchemeRegistry registry = new SchemeRegistry();
			registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
			registry.register(new Scheme("https", sf, 443));
			return new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry), params);
		} catch (Exception e) {
			return new DefaultHttpClient();
		}
	}

	public static byte[] readFromFile(String fileName, int offset, int len) {
		byte[] bArr = null;
		if (fileName != null) {
			File file = new File(fileName);
			if (file.exists()) {
				if (len == -1) {
					len = (int) file.length();
				}
				Log.d(TAG, "readFromFile : offset = " + offset + " len = " + len + " offset + len = " + (offset + len));
				if (offset < 0) {
					Log.e(TAG, "readFromFile invalid offset:" + offset);
				} else if (len <= 0) {
					Log.e(TAG, "readFromFile invalid len:" + len);
				} else if (offset + len > ((int) file.length())) {
					Log.e(TAG, "readFromFile invalid file len:" + file.length());
				} else {
					bArr = null;
					try {
						RandomAccessFile in = new RandomAccessFile(fileName, "r");
						bArr = new byte[len];
						in.seek(offset);
						in.readFully(bArr);
						in.close();
					} catch (Exception e) {
						Log.e(TAG, "readFromFile : errMsg = " + e.getMessage());
						e.printStackTrace();
					}
				}
			} else {
				Log.i(TAG, "readFromFile: file not found");
			}
		}
		return bArr;
	}

	public static Bitmap extractThumbNail(String path, int height, int width, boolean crop) {
		try {
			boolean z;
			Options options;
			Bitmap tmp;
			double beY;
			double beX;
			double d;
			int newHeight;
			int newWidth;
			Bitmap bm;
			Bitmap scale;
			Bitmap cropped;
			if (path != null) {
				if (!path.equals("") && height > 0 && width > 0) {
					z = true;
					Assert.assertTrue(z);
					options = new Options();
					options.inJustDecodeBounds = true;
					tmp = BitmapFactory.decodeFile(path, options);
					if (tmp != null) {
						tmp.recycle();
					}
					Log.d(TAG, "extractThumbNail: round=" + width + "x" + height + ", crop=" + crop);
					beY = ((options.outHeight) * 1.0d) / (height);
					beX = ((options.outWidth) * 1.0d) / (width);
					Log.d(TAG, "extractThumbNail: extract beX = " + beX + ", beY = " + beY);
					d = crop ? beY <= beX ? beX : beY : beY >= beX ? beX : beY;
					options.inSampleSize = (int) d;
					if (options.inSampleSize <= 1) {
						options.inSampleSize = 1;
					}
					while ((options.outHeight * options.outWidth) / options.inSampleSize > 2764800) {
						options.inSampleSize++;
					}
					newHeight = height;
					newWidth = width;
					if (crop) {
						if (beY >= beX) {
							newHeight = (int) ((((newWidth) * 1.0d) * (options.outHeight)) / (options.outWidth));
						} else {
							newWidth = (int) ((((newHeight) * 1.0d) * (options.outWidth)) / (options.outHeight));
						}
					} else if (beY <= beX) {
						newHeight = (int) ((((newWidth) * 1.0d) * (options.outHeight)) / (options.outWidth));
					} else {
						newWidth = (int) ((((newHeight) * 1.0d) * (options.outWidth)) / (options.outHeight));
					}
					options.inJustDecodeBounds = false;
					Log.i(TAG, "bitmap required size=" + newWidth + "x" + newHeight + ", orig=" + options.outWidth
							+ "x" + options.outHeight + ", sample=" + options.inSampleSize);
					bm = BitmapFactory.decodeFile(path, options);
					if (bm != null) {
						Log.e(TAG, "bitmap decode failed");
						return null;
					}
					Log.i(TAG, "bitmap decoded size=" + bm.getWidth() + "x" + bm.getHeight());
					scale = Bitmap.createScaledBitmap(bm, newWidth, newHeight, true);
					if (scale != null) {
						bm.recycle();
						bm = scale;
					}
					if (crop) {
						return bm;
					}
					cropped = Bitmap.createBitmap(bm, (bm.getWidth() - width) >> 1, (bm.getHeight() - height) >> 1,
							width, height);
					if (cropped != null) {
						return bm;
					}
					bm.recycle();
					bm = cropped;
					Log.i(TAG, "bitmap croped size=" + bm.getWidth() + "x" + bm.getHeight());
					return bm;
				}
			}
			z = false;
			Assert.assertTrue(z);
			options = new Options();
			options.inJustDecodeBounds = true;
			tmp = BitmapFactory.decodeFile(path, options);
			if (tmp != null) {
				tmp.recycle();
			}
			Log.d(TAG, "extractThumbNail: round=" + width + "x" + height + ", crop=" + crop);
			beY = ((options.outHeight) * 1.0d) / (height);
			beX = ((options.outWidth) * 1.0d) / (width);
			Log.d(TAG, "extractThumbNail: extract beX = " + beX + ", beY = " + beY);
			if (crop) {
				if (beY <= beX) {
				}
			}
			options.inSampleSize = 1;// (int) d;
			if (options.inSampleSize <= 1) {
				options.inSampleSize = 1;
			}
			while ((options.outHeight * options.outWidth) / options.inSampleSize > 2764800) {
				options.inSampleSize++;
			}
			newHeight = height;
			newWidth = width;
			if (crop) {
				if (beY >= beX) {
					newWidth = (int) ((((newHeight) * 1.0d) * (options.outWidth)) / (options.outHeight));
				} else {
					newHeight = (int) ((((newWidth) * 1.0d) * (options.outHeight)) / (options.outWidth));
				}
			} else if (beY <= beX) {
				newWidth = (int) ((((newHeight) * 1.0d) * (options.outWidth)) / (options.outHeight));
			} else {
				newHeight = (int) ((((newWidth) * 1.0d) * (options.outHeight)) / (options.outWidth));
			}
			options.inJustDecodeBounds = false;
			Log.i(TAG, "bitmap required size=" + newWidth + "x" + newHeight + ", orig=" + options.outWidth + "x"
					+ options.outHeight + ", sample=" + options.inSampleSize);
			bm = BitmapFactory.decodeFile(path, options);
			if (bm != null) {
				Log.i(TAG, "bitmap decoded size=" + bm.getWidth() + "x" + bm.getHeight());
				scale = Bitmap.createScaledBitmap(bm, newWidth, newHeight, true);
				if (scale != null) {
					bm.recycle();
					bm = scale;
				}
				if (crop) {
					return bm;
				}
				cropped = Bitmap.createBitmap(bm, (bm.getWidth() - width) >> 1, (bm.getHeight() - height) >> 1, width,
						height);
				if (cropped != null) {
					return bm;
				}
				bm.recycle();
				bm = cropped;
				Log.i(TAG, "bitmap croped size=" + bm.getWidth() + "x" + bm.getHeight());
				return bm;
			}
			Log.e(TAG, "bitmap decode failed");
			return null;
		} catch (OutOfMemoryError e) {
			Log.e(TAG, "decode bitmap failed: " + e.getMessage());
			return null;
		}
	}

	public static String sha1(String str) {
		if (str == null || str.length() == 0) {
			return null;
		}
		char[] hexDigits = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
			mdTemp.update(str.getBytes());
			char[] buf = new char[(str.length() * 2)];
			int k = 0;
			for (byte byte0 : mdTemp.digest()) {
				int i = k + 1;
				buf[k] = hexDigits[(byte0 >>> 4) & 15];
				k = i + 1;
				buf[i] = hexDigits[byte0 & 15];
			}
			return new String(buf);
		} catch (Exception e) {
			return null;
		}
	}

	public static List<String> stringsToList(String[] src) {
		if (src == null || src.length == 0) {
			return null;
		}
		List<String> result = new ArrayList();
		for (Object obj : src) {
			result.add((String) obj);
		}
		return result;
	}
}
